tibco.admin.Main.loadResource("tibco/admin/deployment/sa/sRsrcList/jss/jss.xml", "tibco.admin", "jss_45", "ljss", false);
tibco.admin.Main.loadResource("tibco/admin/deployment/sa/sRsrcList/jss/xslt.xml", "tibco.admin", "xslt_45", "jss", false);

/*
 * Shared Resources logical code
 * tibco/admin/deployment/sa/sRsrcList
 * Created  by Amour GUO 04/29/2007
 */

if(!jsx3.lang.Package.forName("tibco.admin.deployment.sa.sRsrcList")) {
    /*
    * Define sRsrcList Package if not exist.
    */
    jsx3.lang.Package.definePackage("tibco.admin.deployment.sa.sRsrcList", function (sRsrcList) {
    });
}

/**
 * define sharedResource(Shared Resource List) class;
 * className: tibco.admin.deployment.sa.sRsrcList.SharedResource;
 */
jsx3.lang.Class.defineClass(
        "tibco.admin.deployment.sa.sRsrcList.SharedResource",
        jsx3.lang.Object,
        [tibco.admin.deployment.sa.ServiceAssemblyInterface],
        function(sharedResource) {
            sharedResource.prototype.block = null;
            //public root node.
            sharedResource.prototype.tempCacheDoc = null;
            //temp CDF doc for rollbacking(when click cancel btn)

            sharedResource.prototype.saEntityID = null;
            //Service Assembly Entity ID
            sharedResource.prototype.envEntityID = null;
            //Environment Entity ID
            sharedResource.prototype.profileType = null;
            //Profile type(like HTTP, JDBC, VR, etc.)

            sharedResource.prototype.getButtonText = function() {
                return tibco.admin.Main.getServer().getDynamicProperty("@@lblSRs_45");
            }

            sharedResource.prototype.getNamespace = function() {
                return "tibco.admin";
            }

            sharedResource.getInstance = function() {
                if(!this.instance) {
                    this.instance = new tibco.admin.deployment.sa.sRsrcList.SharedResource();
                }
                return this.instance;
            }

            sharedResource.prototype.onAfterComponentUnloaded = function() {
            }

            sharedResource.prototype.loadComponent = function(parent) {
                var me = this;
                tibco.admin.Main.loadUIResourceAsync(parent, this.getNamespace(), "tibco/admin/deployment/sa/sRsrcList/ui/sResourceList.xml", me, me.componentLoaded);
            }

            /**
             * to set display mode between edit/view mode.
             * @param toEdit {Boolean}   flag to identify if it's edit mode.
             */
            sharedResource.prototype.editSharedResource = function(toEdit) {
                var list = this.block.getDescendantOfName("mtxSharedResources_45");
                if(toEdit) {
                    this.block.getDescendantOfName("btnEdit_45").setDisplay(jsx3.gui.Block.DISPLAYNONE, true);
                    this.block.getDescendantOfName("btnSave_45").setDisplay(jsx3.gui.Block.DISPLAYBLOCK, true);
                    this.block.getDescendantOfName("btnCancel_45").setDisplay(jsx3.gui.Block.DISPLAYBLOCK, true);
                    list.getChild("mcSharedResource_45").setDisplay(jsx3.gui.Block.DISPLAYNONE, true);
                    list.getChild("mcSharedResSelect_45").setDisplay(jsx3.gui.Block.DISPLAYBLOCK, true);
                    var cacheDoc = tibco.admin.Main.getServer().getCache().getDocument("SRProfileDef_45");
                    if(!cacheDoc) {
                        //make call
                    }
                    else {
                        this.tempCacheDoc = cacheDoc.cloneDocument();
                    }
                }
                else {
                    this.block.getDescendantOfName("btnEdit_45").setDisplay(jsx3.gui.Block.DISPLAYBLOCK, true);
                    this.block.getDescendantOfName("btnSave_45").setDisplay(jsx3.gui.Block.DISPLAYNONE, true);
                    this.block.getDescendantOfName("btnCancel_45").setDisplay(jsx3.gui.Block.DISPLAYNONE, true);
                    list.getChild("mcSharedResource_45").setDisplay(jsx3.gui.Block.DISPLAYBLOCK, true);
                    list.getChild("mcSharedResSelect_45").setDisplay(jsx3.gui.Block.DISPLAYNONE, true);
                }
            };

            /**
             * will be called when user select the Shared Resource Definition dropdown.
             * @param selectButton {jsx3.gui.Select} dropdown element.
             */
            sharedResource.prototype.onChangeSharedResourceMapping = function(selectButton) {
                var selectedAttribute = selectButton.getText();
                if(selectedAttribute) {
                    var selectedValue = selectButton.getValue();
                    var list = this.block.getDescendantOfName("mtxSharedResources_45");
                    var recordID = list.getSelectedIds()[0];
                    var cacheDoc = tibco.admin.Main.getServer().getCache().getDocument("SRProfileDef_45");
                    var docNode = cacheDoc.selectSingleNode("//record[@jsxid='" + recordID + "']");
                    docNode.setAttribute("resName", selectedAttribute);
                    docNode.setAttribute("resEntityID", selectedValue);
                    list.repaintData();
                    this.enableSave();
                    //enable Save Btn
                }
            };

            /**
             * destroy "Create Missing Shared Resource" Dialog box from the gui.
             */
            sharedResource.prototype.destroyDialog = function() {
                var pr = tibco.admin.Main.getServer().getJSXByName("blkAdminDesktop_00") || objEvent.target.getServer().getRootBlock();
                var lc = pr.getLastChild();
                if(lc.getClass() == jsx3.Class.forName("jsx3.gui.Dialog")) pr.removeChild(lc);
            };

            /**
             * cancel "Create Missing Shared Resource" Dialog box.
             */
            sharedResource.prototype.cancelSResDef = function() {
                // refresh the Service Assembly List
                var message = new Object();
                message.subject = tibco.admin.deployment.sa.updateSA.EventID.SERVICEASSEMBLY_UPDATED;
                tibco.admin.PubSub.publish(message);
                this.destroyDialog();
            };

            /**
             * Create Missing Shared Resource.
             */
            sharedResource.prototype.saveSResDef = function() {
                //doc_id for creating sResource: updateSRProDefClone_45
                this.callcreateMissingSharedResources();
                this.destroyDialog();
            };

            /**
             * switch to Edit mode.(in Shared Resource List)
             */
            sharedResource.prototype.doEdit = function() {
                this.tempCacheDoc = null;
                this.editSharedResource(true);
                this.block.getDescendantOfName("btnSave_45").setEnabled(jsx3.gui.Form.STATEDISABLED, true);
                //disable save button.
                this.beginEditMode();
            };

            /**
             * enable save button.
             */
            sharedResource.prototype.enableSave = function() {
                this.block.getDescendantOfName("btnSave_45").setEnabled(jsx3.gui.Form.STATEENABLED, true);
            };

            /**
             * rollback all modifications, and switch to View mode.(in Shared Resource List)
             */
            sharedResource.prototype.doCancel = function() {
                if(this.tempCacheDoc) {
                    var mx = this.block.getDescendantOfName("mtxSharedResources_45");
                    mx.setSourceXML(this.tempCacheDoc);
                    mx.repaintData();
                }
                this.tempCacheDoc = null;
                this.editSharedResource(false);
                this.endEditMode();
            };

            /**
             * update modifications of Shared Resource to Backend.
             */
            sharedResource.prototype.doSave = function() {
                this.tempCacheDoc = null;

                //save operation
                this.callupdateSRProfileDefinitionBindings();
            };

            /**
             * get the container type icon url for shared resource list.
             */
            sharedResource.getIcon = function(value) {
                var iconURL = "";
                switch(value) {
                    case "HTTP Server":
                        iconURL = "images/matrix/httpServerSharedResource.png";
                        break;
                    case "HTTP Client":
                        iconURL = "images/matrix/httpClientSharedResource.png";
                        break;
                    case "HTTP":
                        iconURL = "images/matrix/httpServerSharedResource.png";
                        break;
                    case "JDBC":
                        iconURL = "images/matrix/JDBCsharedResource.png";
                        break;
                    case "JMS":
                        iconURL = "images/matrix/JMSsharedResource.png";
                        break;
                    case "RV":
                        iconURL = "images/matrix/RVsharedResource.png";
                        break;
                    case "JNDI":
                        iconURL = "images/matrix/JNDIsharedResource.png";
                        break;
                    case "SSL":
                        iconURL = "images/matrix/SSLsharedResource.png";
                        break;
                    default:
                        iconURL = "images/matrix/unknown.gif";
                }
                iconURL = tibco.admin.Main.resolveAddinImage(iconURL);
                return "../../" + iconURL;
            };

            sharedResource.prototype.definitionHash = {};
            //Hash map which the Shared Resource Definition Dropdown CDF docs are stored in.

            /**
             * Switch the dropdown options to proper ones after user edit the Shared Resource matrix.
             * Will be called on "Before Edit" of Matrix(Shared Resource List)
             * @param objGrid     {jsx3.gui.Matrix}        affected Matrix Object
             * @param objColumn   {jsx3.gui.Matrix.Column} affected Column
             * @param strRecordId {String} CDF record id for the affected now
             */
            sharedResource.prototype.onPropertyBeforeEdit = function(objGrid, objColumn, strRecordId) {
                var objRecord = objGrid.getRecordNode(strRecordId);
                this.profileType = objRecord.getAttribute("profileType");
                if(this.definitionHash[this.profileType]) {
                    this.beforeEditCallBack(this.profileType);
                }
                else {
                    objMask = objColumn.getChild("selSharedResDef_45");
                    objMask.setEnabled(jsx3.gui.Form.STATEDISABLED);
                    var blankXML = new jsx3.xml.Document();
                    blankXML.loadXML('<data jsxid="jsxroot"><record jsxtext="' + tibco.admin.Main.getServer().getDynamicProperty("@@optLoading_45A") + '"/></data>');
                    objMask.setSourceXML(blankXML);
                    this.callgetSharedResourceDefinitions();
                }
            };

            /**
             * to repaint dropdown, and get shared resource profile type
             * @param profileType {String} shared resource profile type(like HTTP,JDBC,etc.)
             */
            sharedResource.prototype.beforeEditCallBack = function(profileType) {
                var objMask = this.block.getDescendantOfName("selSharedResDef_45");
                objMask.setEnabled(jsx3.gui.Form.STATEENABLED);
                var myXML = this.definitionHash[profileType];
                objMask.setSourceXML(myXML);
            };

            /**
             * Define a CSS Identifier for faking a Dropdown box.
             */
            sharedResource.prototype.setCSS = function() {
                var arrowmask = tibco.admin.Main.getServer().resolveURI("JSX/images/select/arrowmask.gif");
                jsx3.html.createRule(".formSelectmask", " position: absolute;top: 0px; left: 0; width: 100%; height: 100%;background-image:url(" + arrowmask + "); background-repeat:no-repeat;background-position:right 3px;border-top:1px solid #A6A6AF;border-right:1px solid #E6E6E6;border-bottom:1px solid #E6E6E6;border-left:1px solid #A6A6AF;background-color:#fff;");
            };

            /* --- callgetSRProfileDefinitionBindings --- */

            //call this method to begin the service call (tibco.admin.deployment.sa.sRsrcList.SharedResource.callgetSRProfileDefinitionBindings();)
            sharedResource.prototype.callgetSRProfileDefinitionBindings = function() {
                var objService = tibco.admin.Main.loadService("tibco.admin", "tibco/admin/deployment/sa/sRsrcList/rules/getSRProfileDefinitionBidings.xml", "getSRProfileDefinitionBindings");
                objService.saEntityID = this.saEntityID;
                objService.setEndpointURL(tibco.admin.util.ServiceHelper.getDeploymentEndpointURL());
                var me = this;
                //subscribe and call
                objService.subscribe(jsx3.net.Service.ON_SUCCESS, me, me.ongetSRProfileDefinitionBindingsSuccess);
                objService.doCall();
            };

            sharedResource.prototype.ongetSRProfileDefinitionBindingsSuccess = function(objEvent) {
                var mx = this.block.getDescendantOfName("mtxSharedResources_45");
                mx.setSourceXML(tibco.admin.Main.getServer().getCache().getDocument("SRProfileDef_45"));
                mx.repaintData();

            };

            //call this method to begin the service call (tibco.admin.deployment.sa.sRsrcList.SharedResource.callgetSharedResourceDefinitions();)
            sharedResource.prototype.callgetSharedResourceDefinitions = function() {
                var objService = tibco.admin.Main.loadService("tibco.admin", "tibco/admin/deployment/sa/sRsrcList/rules/getSharedResourceDefinitions.xml", "getSharedResourceDefinitions");
                //satya//for update event//objService.parentName = sharedResource.parentServiceAssembly;

                objService.envEntityID = this.envEntityID;
                objService.profileType = this.profileType;
                //just for test.
                objService.setEndpointURL(tibco.admin.util.ServiceHelper.getDeploymentEndpointURL());
                var me = this;
                //subscribe and call
                objService.subscribe(jsx3.net.Service.ON_SUCCESS, me, me.ongetSharedResourceDefinitionsSuccess);
                objService.doCall();
            };

            sharedResource.prototype.ongetSharedResourceDefinitionsSuccess = function(objEvent) {
                //beforeEditCallBack
                var myXML = tibco.admin.Main.getServer().getCache().getDocument("sResDef_45");
                if(objEvent.target.profileType) {
                    this.definitionHash[objEvent.target.profileType] = myXML;
                    this.beforeEditCallBack(objEvent.target.profileType);
                }
            };

            //call this method to begin the service call (eg.service.callupdateSRProfileDefinitionBindings();)
            sharedResource.prototype.callupdateSRProfileDefinitionBindings = function() {
                var objService = tibco.admin.Main.loadService("tibco.admin", "tibco/admin/deployment/sa/sRsrcList/rules/updateSRProfileDefBindingsRule.xml", "updateSRProfileDefinitionBindings");

                var myCache = tibco.admin.Main.getServer().getCache();
                var myXML = myCache.getDocument("SRProfileDef_45");

                objService.saEntityID = this.saEntityID;
                objService.setEndpointURL(tibco.admin.util.ServiceHelper.getDeploymentEndpointURL());
                var me = this;
                //subscribe and call
                objService.subscribe(jsx3.net.Service.ON_SUCCESS, me, me.onupdateSRProfileDefinitionBindingsSuccess);
                objService.doCall();
            };

            sharedResource.prototype.paintMissing = function() {
                var mx = tibco.admin.Main.getServer().getJSXByName("mtxCreateDef_45");

                var myCache = tibco.admin.Main.getServer().getCache();
                var myXML = myCache.getDocument("updateSRProDefResp_45");
                var cloneXML = myXML.cloneDocument();
                myCache.setDocument("updateSRProDefClone_45", cloneXML);
                //for creating shared resource

                mx.setSourceXML(myXML);
                mx.repaintData();
            };

            sharedResource.prototype.onupdateSRProfileDefinitionBindingsSuccess = function(objEvent) {
                this.editSharedResource(false);
                this.endEditMode();
                var myXML = tibco.admin.Main.getServer().getCache().getDocument("updateSRProDefResp_45");
                var missings = myXML.selectNodes("//record/record");
                //to get all the missing nodes to decide if neet to popup a prompt window or not.
                if(missings.getLength() > 0) {
                    var parent = tibco.admin.Main.getServer().getJSXByName("blkAdminDesktop_00") || objEvent.target.getServer().getRootBlock();
                    var me = this;
                    tibco.admin.Main.loadUIResourceAsync(parent, "tibco.admin", "tibco/admin/deployment/sa/sRsrcList/ui/newSResDef.xml", me, me.paintMissing, true);
                }

                // refresh the Service Assembly List
                var message = new Object();
                message.subject = tibco.admin.deployment.sa.updateSA.EventID.SERVICEASSEMBLY_UPDATED;
                tibco.admin.PubSub.publish(message);
            };

            //call this method to begin the service call (tibco.admin.deployment.sa.sRsrcList.SharedResource.callcreateMissingSharedResources();)
            sharedResource.prototype.callcreateMissingSharedResources = function() {
                var objService = tibco.admin.Main.loadService("tibco.admin", "tibco/admin/deployment/sa/sRsrcList/rules/createMissingSResourceRules.xml", "createMissingSharedResources");

                objService.setEndpointURL(tibco.admin.util.ServiceHelper.getDeploymentEndpointURL());
                var me = this;
                //subscribe and call
                objService.subscribe(jsx3.net.Service.ON_SUCCESS, me, me.oncreateMissingSharedResourcesSuccess);
                objService.doCall();
            };

            sharedResource.prototype.oncreateMissingSharedResourcesSuccess = function(objEvent) {
                // load created share resources result dialog.
                var parent = tibco.admin.Main.getServer().getJSXByName("blkAdminDesktop_00") || objEvent.target.getServer().getRootBlock();
                var me = this;
                tibco.admin.Main.loadUIResourceAsync(parent, "tibco.admin", "tibco/admin/deployment/sa/sRsrcList/ui/createSRDResult.xml", me, me.paintResult, true);
            };

            sharedResource.prototype.paintResult = function() {

                var mx = tibco.admin.Main.getServer().getJSXByName("mtxCreateResult_45");
                //sharedResource.block.getDescendantOfName("mtxCreateResult_45");

                var myCache = tibco.admin.Main.getServer().getCache();
                var myXML = myCache.getDocument("createMissingSRResponse_45");

                mx.setSourceXML(myXML);
                //not finished yet
                mx.repaintData();
                //not finished yet
            };

            //SubPub(SERVICEASSEMBLY_ROW_SELECTED) Callback func.
            sharedResource.prototype.setSharedResource = function(message) {
                if(this.isInEditMode()) {
                    return;
                }
                if(!message.entityID) return false;
                this.saEntityID = message.entityID;
                this.envEntityID = message.envEntityID;
                this.callgetSRProfileDefinitionBindings();
            }

            sharedResource.prototype.subscribeAll = function() {
                var me = this;
                //Subscribe the SERVICEASSEMBLY_ROW_SEECTED event.
                tibco.admin.PubSub.subscribe(tibco.admin.deployment.saList.EventID.SERVICEASSEMBLY_ROW_SELECTED, me, me.setSharedResource);
            };

            sharedResource.prototype.unsubscribeAll = function() {
                //Unsubscribe the SERVICEASSEMBLY_ROW_SELECTED event.
                tibco.admin.PubSub.unsubscribe(tibco.admin.deployment.saList.EventID.SERVICEASSEMBLY_ROW_SELECTED, this);

            };

            /**
             * MUST appear in "onAfterDeserialize" textarea.
             */
            sharedResource.prototype.componentLoaded = function(objEvent) {
                if(objEvent.status == "SUCCESS") {
                    this.block = objEvent.obj;
                    var me = this;
                    this.block.handler = me;
                    this.setCSS();
                    this.subscribeAll()
                    this.block.getDescendantOfName("selSharedResDef_45").
                            setDefaultText(tibco.admin.Main.getServer().getDynamicProperty("@@SelDefaultText_45A"));
                }
                else {
                    if(objEvent.exception)
                    {
                        tibco.admin.Main.logException(objEvent.exception, objEvent.message);
                    }
                    else {
                        jsx3.log(objEvent.message);
                    }
                }
            }

            sharedResource.prototype.destroyPlugin = function(objTarget, objParent) {

            }

            sharedResource.prototype.onDestroy = function() {
                this.unsubscribeAll();
                this.block = null;
                this.definitionHash = {};
            }

            sharedResource.prototype.getComponentPath = function() {
                return  "tibco/admin/deployment/sa/sRsrcList/component.xml"
            }

        });